//注册逻辑

//0.获取元素
const form = document.querySelector('form');
const usernameInp = document.querySelector('.username>input');
const nicknameInp = document.querySelector('.nickname>input');
const passwordInp = document.querySelector('.password>input');
const rePasswordInp = document.querySelector('.re_password>input');
const info = document.querySelector('.pone');


// 1.给表单绑定提交事件
form.addEventListener('submit', async e => {
    e = e || window.event;
    try{e.preventDefault()} catch(err) {e.returnValue = false};
    //1-1.获取数据
    const username = usernameInp.value;
    const nickname = nicknameInp.value;
    const password = passwordInp.value;
    const rePassword = rePasswordInp.value;

    //1-2.非空验证
    if(!username || !nickname || !password || !rePassword) return window.alert('请完整填写表单');
    //1-3.判断两次输入密码是否一致
    if(password !== rePassword) {
        info.innerText = '两次输入密码不一致，请重新输入';
        info.classList.add('active');
        return;
    }
    //1-2.发送请求
    const data = `username=${username}&nickname=${nickname}&password=${password}&rpassword=${rePassword}`;
    const res = await pAjax({
        url: 'http://localhost:8888/users/register',
        method: 'POST',
        data,
        dataType: 'json'
    })
    if(res.code === 0) {
        info.innerText = '用户名已存在，请重新输入';
        info.classList.add('active');
        return;
    }
    if(res.code === 1) {
        window.alert('注册成功，点击确定跳转回到登录页');
        window.location.href = './login.html';
    }
})


